package com.farm.util.sso;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import com.farm.core.auth.domain.LoginUser;
import com.farm.util.cache.FarmCacheName;
import com.farm.util.cache.FarmCaches;
import com.farm.web.constant.FarmConstant;

/**
 * 配合单点登陆，缓存客户端的单点登陆信息
 * 
 * @author macpl
 *
 */
public class SsoLoginInfos {
	/**
	 * 写入登陆信息，客户端和服务器端的sessionid都要写入
	 * 
	 * @param sessionId1
	 * @param sessionId2
	 * @param user
	 */
	public static void putSsoCache(String sessionId1, String sessionId2, LoginUser user) {
		Map<String, Object> sessionUser = new HashMap<String, Object>();
		sessionUser.put("user", user);
		sessionUser.put("sessionId1", sessionId1);
		sessionUser.put("sessionId2", sessionId2);
		FarmCaches.getInstance().putCacheData(sessionId1, sessionUser, FarmCacheName.SsoSessionCache);
		FarmCaches.getInstance().putCacheData(sessionId2, sessionUser, FarmCacheName.SsoSessionCache);
	}

	/**注销，只要传入服务器端的sessionid，就会同时注销客户端和服务器端的session
	 * @param sessionId
	 */
	public static void logoutSsoCache(HttpSession session) {
		// 刪除当前session单点登陆的信息
		FarmCaches.getInstance().removeCacheData(session.getId(), FarmCacheName.SsoSessionCache);
		session.setAttribute(FarmConstant.SESSION_USEROBJ, null);
	}

	/**用户客户端，或者服务器端的sessionid，兑换用户信息，如果服务器端注销后，用户客户端的session也无法获取用户信息
	 * @param sessionId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static LoginUser getSsoCache(String sessionId) {
		Map<String, Object> sessionUser = (Map<String, Object>) FarmCaches.getInstance().getCacheData(sessionId,
				FarmCacheName.SsoSessionCache);
		if (sessionUser == null) {
			return null;
		}
		LoginUser user = (LoginUser) sessionUser.get("user");
		String sessionId1 = (String) sessionUser.get("sessionId1");
		String sessionId2 = (String) sessionUser.get("sessionId2");
		{
			Map<String, Object> sessionUser1 = (Map<String, Object>) FarmCaches.getInstance().getCacheData(sessionId1,
					FarmCacheName.SsoSessionCache);
			Map<String, Object> sessionUser2 = (Map<String, Object>) FarmCaches.getInstance().getCacheData(sessionId2,
					FarmCacheName.SsoSessionCache);
			if (sessionUser1 != null && sessionUser2 != null && sessionUser1.get("user") != null
					&& sessionUser2.get("user") != null && sessionUser1.get("user").equals(sessionUser2.get("user"))) {
				return user;
			} else {
				FarmCaches.getInstance().removeCacheData(sessionId1, FarmCacheName.SsoSessionCache);
				FarmCaches.getInstance().removeCacheData(sessionId2, FarmCacheName.SsoSessionCache);
				return null;
			}
		}
	}
}
